<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/4/30 11:24
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Log;

class OperationLogMiddleware
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (app()->environment('production')) {
            if (auth('api')->check()) {
                $userString = join(' ', array_filter([auth('api')->id(), auth('api')->user()->name, auth('api')->user()->email]));
                $uri = $request->path();
                $method = $request->method();
                $userAgent = (new Agent())->getUserAgent();
                $ip = $request->getClientIp();
                $logMsg = join(' | ', [$userString, $method . ' ' . $uri . ' ', $userAgent, $ip]);
                Log::channel('operation')->info($logMsg . PHP_EOL);
            }
        }
        return $next($request);
    }
}
